//
//  EmoticonViewController.swift
//  Emoticon
//
//  Created by 袁航 on 15/8/6.
//  Copyright © 2015年 yuanhang. All rights reserved.
//

import UIKit
// cell重用标识符
private let EmoticonCollectionViewID = "EmoticonCollectionViewID"
class EmoticonViewController: UIViewController {
    // 定义变量,记录点击图标的个数
    var clickItem = 0
    //MARK:- 定义表情点击回调
    let emoticonClickCallBack:(emoticon: Emoticons) -> ()
    // 重写构造方法
    init(emoticonClick: (emoticon: Emoticons) -> ()) {
        emoticonClickCallBack = emoticonClick
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:- 键盘界面
    var keyboardView: UIView {
        return view
    }
    // 布局界面,设置
    override func loadView() {
        super.loadView()
        setupUI()
    }
    // 设置UI
    private func setupUI() {
        // 准备控件
        prepareToolBar()
        prepareCollectionView()
        // 设置约束
        let views = ["toolBar" : toolBar, "collectionView" : collectionView]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolBar(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
    }
    // 准备collectionView
    private func prepareCollectionView() {
        view.addSubview(collectionView)
        collectionView.backgroundColor = UIColor.whiteColor()
        collectionView.registerClass(EmoticonCollectionViewCell.self, forCellWithReuseIdentifier: EmoticonCollectionViewID)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.translatesAutoresizingMaskIntoConstraints = false
    }
    
    // 准备toolBar
    private func prepareToolBar() {
        // 添加到主视图上
        view.addSubview(toolBar)
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        // 创建按钮数组
        var items = [UIBarButtonItem]()
        // tag值
        var index = 0
        // 遍历package创建按钮(根据组名)
        for emoticonPackage in EmoticonPackage.EmoticonPackageModels {
            let buttonTitle = emoticonPackage.emoticonInfoModel?.group_name_cn
            // 添加按钮
            items.append(UIBarButtonItem(title: buttonTitle, style: UIBarButtonItemStyle.Plain, target: self, action: "toolBarItemClick:"))
            // 绑定tag值
            items.last?.tag = index++
            // 追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 去掉最后一根弹簧
        items.removeLast()
        // 设置按钮
        toolBar.items = items
    }
    //MARK:- 工具栏按钮点击事件处理
    func toolBarItemClick(item: UIBarButtonItem) {
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    // MARK:- 懒加载控件
    private lazy var toolBar = UIToolbar()
    private lazy var collectionView = EmoCollectionView()
    // MARK:- 懒加载数据
    private lazy var emoticonPackages = EmoticonPackage.EmoticonPackageModels
}

//MARK:- 准备collectionView
private class EmoCollectionView: UICollectionView {
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: EmoCollectionViewFlowLayout())
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
//MARK:- 准备collectionViewFlowlayout
private class EmoCollectionViewFlowLayout: UICollectionViewFlowLayout {
    // 设置基本属性
    override func prepareLayout() {
        // 设置基本属性
        let w_h = collectionView!.bounds.width / 7.0
        let topInset = (collectionView!.frame.height - 3 * w_h) * 0.499
        itemSize = CGSize(width: w_h, height: w_h)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        sectionInset = UIEdgeInsetsMake(topInset, 0, topInset, 0)
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.pagingEnabled = true
    }
}
// MARK:- 自定义collectionViewCell(私有类,只有自身能访问)
private class EmoticonCollectionViewCell: UICollectionViewCell {
    // 定义模型数据,显示图片
    var emoticon: Emoticons? {
        didSet {
            imageBtn.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            imageBtn.setImage(UIImage(contentsOfFile: emoticon!.pngImagePath), forState: UIControlState.Normal)
            if emoticon!.remove {
                imageBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                imageBtn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置UI界面
    private func setupUI() {
        let rect = CGRectInset(bounds, 2, 2)
        imageBtn.userInteractionEnabled = false
        imageBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        imageBtn.frame = rect
        addSubview(imageBtn)
    }
    //MARK:- 懒加载控件
    private lazy var imageBtn = UIButton()
}

//MARK:- collectionView的数据源方法
extension EmoticonViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return emoticonPackages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emoticonPackages[section].emoticonInfoModel?.emoticonModels.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCollectionViewID, forIndexPath: indexPath) as! EmoticonCollectionViewCell
        cell.emoticon = emoticonPackages[indexPath.section].emoticonInfoModel!.emoticonModels[indexPath.row]
        
        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 取出表情模型
        let emoticon = emoticonPackages[indexPath.section].emoticonInfoModel!.emoticonModels[indexPath.row]
        // 判断是否是删除按钮后,回调.如果是删除按钮,就不回调
        emoticonClickCallBack(emoticon: emoticon)
        // 判断是否是删除箭头(如果是删除箭头,就不在更改模型数据)
        if emoticon.remove {
            return
        }
        // 如果是第一次点击把表情添加到最近使用的模型中
        if emoticon.clickCount == 0 {
            // 如果图表个数超过20个,不再存储,直接返回
            if clickItem > 19 {
                clickItem = 20
                return
            }
            // 更改最近点击的模型数据
            emoticonPackages[0].emoticonInfoModel?.emoticonModels[clickItem++] = emoticon
            // 记录表情被点击过,次数加1
            emoticon.clickCount++
        } else {
            emoticon.clickCount++
        }
        // 重新排序最近表情数组(如果是点击的最近表情数组，就不排序)
        if indexPath.section == 0{
            return
        } else {
            emoticonPackages[0].emoticonInfoModel!.emoticonModels.sortInPlace({ (emoticon1, emoticon2) -> Bool in
                return emoticon1.clickCount > emoticon2.clickCount
            })
        }
        // 刷新数据(只刷新最近表情组)
        collectionView.reloadSections(NSIndexSet(index: 0))  
    }
}


